/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.commons.core;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * {@link Resource} implementation for class path resources. Uses either a
 * given {@link ClassLoader} or a given {@link Class} for loading resources.
 *
 * <p>Supports resolution as {@code java.io.File} if the class path
 * resource resides in the file system, but not for resources in a JAR.
 * Always supports resolution as URL.
 *
 * @author Mr.css 2018年7月13日 上午11:15:10
 */
public class ClassPathResource {

    private ClassPathResource() {
    }

    /**
     * 获取ClassLoader
     * <p>
     * return {{@link Thread#getContextClassLoader}} first,
     * if cause exception, return {{@link ClassLoader#getSystemClassLoader}}.
     *
     * @return ClassLoader
     * @see ClassLoader
     */
    public static ClassLoader getClassLoader() {
        try {
            return Thread.currentThread().getContextClassLoader();
        } catch (Exception ignore) {
            // Cannot access thread context ClassLoader - falling back...
        }
        return ClassLoader.getSystemClassLoader();
    }

    /**
     * 获取URL
     * <p>
     * Return {{@link ClassLoader#getResource}}, the same as {{@link #getInputStream}}.
     * You can also get a Url from a jar(springboot-jar).
     *
     * @param file path, do not star with '/' when get resource from jar(springboot-jar)
     * @return Url
     */
    @Nullable
    public static URL getUrl(String file) {
        ClassLoader loader = getClassLoader();
        return loader.getResource(file);
    }

    /**
     * 返回资源的路径，不能直接使用，因为返回的路径，可能是jar包内的目录
     * <p>
     * Return resource path which decode by URLDecoder, can not use directly, because maybe in a jar.
     *
     * @return resource path
     */
    public static String getResourcePath(String path) throws FileNotFoundException {
        try {
            URL u = getUrl(path);
            if (u == null) {
                throw new FileNotFoundException("File not found: " + path);
            } else {
                return URLDecoder.decode(u.getPath(), Charset.defaultCharset().name());
            }
        } catch (UnsupportedEncodingException e) {
            throw new FileNotFoundException("File path decode failed: " + e.getMessage());
        }
    }

    /**
     * class path root
     *
     * @return resource path
     */
    public static String getClassPath() throws FileNotFoundException {
        return getResourcePath("");
    }

    /**
     * return {{@link ClassLoader#getResourceAsStream }},
     * {{@link ClassLoader#getResourceAsStream }} is the same as {{@link ClassLoader#getSystemResourceAsStream }}
     *
     * @param file path, do not star with '/' when get resource from jar(springboot-jar)
     * @return InputStream
     * @throws IOException if an I/O exception occurs.
     */
    @NotNull
    public static InputStream getInputStream(String file) throws IOException {
        ClassLoader loader = getClassLoader();
        URL url = loader.getResource(file);
        if (url == null) {
            throw new FileNotFoundException("File not found: " + file);
        } else {
            return url.openStream();
        }
    }


    /**
     * Convert the given URL as returned from the ClassLoader into a {@link Resource}.
     * The default implementation simply creates a {@link UrlResource} instance.
     * <p>
     * Find all class location resources with the given path via the ClassLoader.
     *
     * @param path the absolute path within the classpath (never a leading slash)
     * @return a mutable Set of matching Resource instances
     * @see java.lang.ClassLoader#getResources
     * @see org.springframework.core.io.Resource
     */
    public static Resource getResource(String path) throws IOException {
        URL url = getClassLoader().getResource(path);
        if (url == null) {
            throw new FileNotFoundException("File not found: " + path);
        } else {
            return new UrlResource(url);
        }
    }

    /**
     * Convert the given URL as returned from the ClassLoader into a {@link Resource}.
     * The default implementation simply creates a {@link UrlResource} instance.
     * <p>
     * Find all class location resources with the given path via the ClassLoader.
     *
     * @param path the absolute path within the classpath (never a leading slash)
     * @return a mutable Set of matching Resource instances
     * @see java.lang.ClassLoader#getResources
     * @see org.springframework.core.io.Resource
     */
    public static Set<Resource> getResources(String path) throws IOException {
        Set<Resource> result = new LinkedHashSet<>(16);
        ClassLoader loader = getClassLoader();
        Enumeration<URL> urls = loader.getResources(path);
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            result.add(new UrlResource(url));
        }
        return result;
    }


    /**
     * @param dir      path, do not star with '/' when get resource from jar(springboot-jar)
     * @param function a callback
     * @throws IOException if an I/O exception occurs.
     */
    public static void eachResources(String dir, Consumer<InputStream> function) throws IOException {
        ClassLoader loader = getClassLoader();
        Enumeration<URL> urls = loader.getResources(dir);
        URL url;
        while (urls.hasMoreElements()) {
            url = urls.nextElement();
            if (url != null) {
                function.accept(url.openStream());
            }
        }
    }

    /**
     * @param dir      path, do not star with '/' when get resource from jar(springboot-jar)
     * @param function a callback
     * @param <E>      result type
     * @return arrayList
     * @throws IOException if an I/O exception occurs.
     */
    public static <E> List<E> eachResources(String dir, Function<InputStream, E> function) throws IOException {
        ClassLoader loader = getClassLoader();
        Enumeration<URL> urls = loader.getResources(dir);
        List<E> res = new ArrayList<>();
        URL url;
        while (urls.hasMoreElements()) {
            url = urls.nextElement();
            if (url != null) {
                res.add(function.apply(url.openStream()));
            }
        }
        return res;
    }

    /**
     * path of project
     *
     * @return path of project
     */
    public static String getSystemUserDir() {
        return System.getProperty("user.dir");
    }

}
